package com.zjt.pictureselector;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zjt.pictureselector.Util.PictureUtil;
import com.zjt.pictureselector.adapter.FolderAdapter;
import com.zjt.pictureselector.adapter.PictureAdapter;
import com.zjt.pictureselector.model.FolderBean;
import com.zjt.pictureselector.model.MediaBean;

import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionGen;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2017/11/8 0008 下午 5:37
 */

public class PictureSelectorActivity extends AppCompatActivity {

    public static final String SELECT_LIST = "SELECT_LIST";
    private static final int MESSAGE_GET_DATA_SUCCESS = 100;
    private static final int MAX_SELECT_NUM = 9;
    private RecyclerView imageRecyclerView;
    private RecyclerView folderRecyclerView;
    private TextView tvFolderName;
    private TextView tvConfirm;
    private FrameLayout folderFrameLayout;
    private LinearLayout folderLinearLayout;

    private PictureAdapter pictureAdapter;
    private FolderAdapter folderAdapter;
    private List<FolderBean> allFolderList;
    private List<MediaBean> selectMediaList;
    private FolderBean mFolder;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_GET_DATA_SUCCESS:
                    initDataView((List<FolderBean>) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_selector);
        selectMediaList = getIntent().getParcelableArrayListExtra(SELECT_LIST);
        requestPermission();
        initImageView();
        initFolderView();
        initMediaData();
    }

    private void requestPermission() {
        PermissionGen.with(PictureSelectorActivity.this)
                .addRequestCode(10)
                .permissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void initImageView(){
        imageRecyclerView = (RecyclerView) this.findViewById(R.id.rv_image);
        pictureAdapter = new PictureAdapter(this);
        pictureAdapter.setMaxSelectNum(MAX_SELECT_NUM);
        pictureAdapter.setItemSelectListener(new PictureAdapter.OnItemSelectListener() {
            @Override
            public void onClick(int num) {
                setSelectImageNum(num);
            }
        });
        imageRecyclerView.setAdapter(pictureAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        imageRecyclerView.setLayoutManager(gridLayoutManager);
    }

    private void initFolderView(){
        tvFolderName = (TextView) this.findViewById(R.id.tv_folder_name);
        tvConfirm = (TextView) this.findViewById(R.id.tv_confirm);
        folderLinearLayout = (LinearLayout) this.findViewById(R.id.ll_folder);
        folderFrameLayout = (FrameLayout) this.findViewById(R.id.fl_folder);
        folderRecyclerView = (RecyclerView) this.findViewById(R.id.rv_folder);

        folderAdapter = new FolderAdapter(this, allFolderList);
        folderAdapter.setOnFolderSelectListener(new FolderAdapter.OnFolderSelectListener() {
            @Override
            public void OnFolderSelect(FolderBean folder) {
                selectFolder(folder);
            }
        });
        folderRecyclerView.setAdapter(folderAdapter);
        folderRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        folderFrameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (folderLinearLayout.getVisibility() == View.VISIBLE) {
                    closeFolder();
                } else {
                    openFolder();
                }
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmSelect();
            }
        });
    }

    private void initMediaData(){
        PictureUtil.getAllMedia(this, new PictureUtil.PictureDataCallback() {
            @Override
            public void onSuccess(List<FolderBean> folderBeanList) {
                Message message = new Message();
                message.what = MESSAGE_GET_DATA_SUCCESS;
                message.obj = folderBeanList;
                handler.sendMessage(message);
            }
        });
    }

    private void initDataView(List<FolderBean> folderBeanList){
        allFolderList = folderBeanList;
        initSelectData(allFolderList.get(0).getMediaBeanList());
        pictureAdapter.refreshData(allFolderList.get(0).getMediaBeanList());
        folderAdapter.refresh(allFolderList);
    }

    private void initSelectData(List<MediaBean> mediaBeanList){
        if (selectMediaList == null) {
            selectMediaList = new ArrayList<>();
        }
        setSelectImageNum(selectMediaList.size());
        for (MediaBean selectMedia: selectMediaList) {
            for(MediaBean mediaBean : mediaBeanList) {
                if (selectMedia.getPath().equals(mediaBean.getPath()) && !mediaBean.isSelect()) {
                    pictureAdapter.selectMedia(mediaBean);
                    break;
                }
            }
        }
    }

    private void selectFolder(FolderBean folder) {
        if (folder != null && pictureAdapter != null && !folder.equals(mFolder)) {
            mFolder = folder;
            tvFolderName.setText(folder.getFolderName());
            imageRecyclerView.scrollToPosition(0);
            pictureAdapter.refreshData(folder.getMediaBeanList());
            closeFolder();
        }
    }

    private void setSelectImageNum(int num){
        if (num == 0) {
            tvConfirm.setText("确定");
        } else {
            tvConfirm.setText("确定(" + num + "/" + MAX_SELECT_NUM + ")");
        }
    }

    private void confirmSelect(){
        if (selectMediaList != null && !selectMediaList.isEmpty()) {
            selectMediaList.clear();
        }
        selectMediaList = pictureAdapter.getSelectList();
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(SELECT_LIST, (ArrayList<MediaBean>) selectMediaList);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void openFolder() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(folderRecyclerView, "translationY",
                folderRecyclerView.getHeight(), 0).setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                folderLinearLayout.setVisibility(View.VISIBLE);
            }
        });
        animator.start();
    }

    private void closeFolder() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(folderRecyclerView, "translationY",
                0, folderRecyclerView.getHeight()).setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                folderLinearLayout.setVisibility(View.GONE);
            }
        });
        animator.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && folderLinearLayout.getVisibility() == View.VISIBLE) {
            closeFolder();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
